<template>
  <div class="app-container">
    <el-drawer title :visible.sync="showFlag" size="95%">
      <div style="padding:0 20px;">
        <el-table v-loading="loading" :data="iqcList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" align="center" width="50px" prop="issueCode">
            <template slot-scope="scope">
              <span>{{scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column label="送检单号" width="150px" align="center" prop="iqcCode" />
          <el-table-column label="供应商" width="120px" align="center" prop="vendorName" />
          <el-table-column label="状态" width="120px" align="center" prop="fqcstatus">
            <template
              slot-scope="scope"
            >{{ scope.row.fqcstatus =='0' ? "未检验" :scope.row.fqcstatus =='1'?"已检验":"--" }}</template>
          </el-table-column>
          <el-table-column label="物料编码" width="120px" align="center" prop="itemCode" />
          <el-table-column label="物料名称" width="120px" align="center" prop="itemName" />
          <el-table-column label="规格型号" width="120px" align="center" prop="specification" />
          <el-table-column label="送检数量" width="100px" align="center" prop="quantityCheck" />
          <el-table-column label="抽检数量" width="100px" align="center" prop="quantitySpotCheck" />
          <el-table-column label="合格数量" width="100px" align="center" prop="receiveQty" />
          <el-table-column label="不合格数量" width="120px" align="center" prop="quantityUnqualified" />
          <el-table-column label="检验结果" width="120px" align="center" prop="checkResult">
            <template
              slot-scope="scope"
            >{{ scope.row.checkResult =='0' ? "不合格" :scope.row.checkResult =='1'?"合格":"" }}</template>
          </el-table-column>
          <el-table-column label="检验员" width="120px" align="center" prop="inspector" />
          <el-table-column label="检验时间" width="120px" align="center" prop="inspectDate" />
          <!-- <el-table-column label="审核员" width="120px" align="center" prop="auditor"/> -->
          <!-- <el-table-column label="审核时间" width="120px" align="center" prop="auditDate"/> -->
          <el-table-column
            label="操作"
            align="center"
            width="100px"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.fqcstatus=='0'"
                @click="handleView(scope.row)"
              >检验</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-share"
                v-if="scope.row.fqcstatus=='1'"
                @click="viewReport(true, scope.row)"
              >查看报表</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 检验页面 -->
        <el-drawer
          :title="title"
          :visible.sync="open"
          size="90%"
          :before-close="cancel"
          custom-class="demo-drawer"
          :append-to-body="true"
        >
          <div class="demo-drawer__content dialogContent" style="padding:0 20px">
            <el-form ref="form" :model="form" :rules="rules" label-width="auto">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="物料名称:" prop="itemName">
                    <el-input v-model="form.itemName" placeholder />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="规格型号:" prop="specification">
                    <el-input v-model="form.specification" placeholder />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="送检单号:" prop="iqcCode">
                    <el-input v-model="form.iqcCode" placeholder />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="供应商:" prop="vendorName">
                    <el-input v-model="form.vendorName" placeholder />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="6">
                  <el-form-item label="送检数量:" prop="quantityCheck">
                    <el-input v-model="form.quantityCheck" placeholder />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="检验时间:" prop="inspectDate">
                    <el-date-picker
                      clearable
                      v-model="form.inspectDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择检验日期"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="抽样数量" prop="quantitySpotCheck">
                    <el-input-number
                      :controls="false"
                      v-model="form.quantitySpotCheck"
                      :max="form.quantityCheck"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="合格数量:" prop="receiveQty">
                    <el-input v-model="form.receiveQty" placeholder />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="不合格数量:" prop="quantityUnqualified">
                    <el-input v-model="form.quantityUnqualified" placeholder />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 中间的table -->
              <el-row>
                <el-table v-loading="loading1" :data="templateList" :span-method="objectSpanMethod">
                  <!-- <el-table-column type="index" label="序号" width="50" :index="indexMethod"></el-table-column> -->
                  <el-table-column label="检查项目" align="center" prop="inspectionItem" width="160px" />
                  <el-table-column label="缺陷等级" align="center" prop="defectLevel">
                    <template
                      slot-scope="scope"
                    >{{ scope.row.defectLevel =='1' ? "A" :scope.row.defectLevel =='2'?"B":"C" }}</template>
                  </el-table-column>
                  <el-table-column
                    label="检验标准及检验方法"
                    align="center"
                    prop="inspectionStandard"
                    width="260px"
                  />
                  <el-table-column
                    label="检验方式及工具"
                    align="center"
                    prop="inspectionMethod"
                    width="160px"
                  />
                  <el-table-column
                    label="抽样标准"
                    align="center"
                    prop="samplingStandards"
                    width="260px"
                  />
                  <el-table-column label="判定" align="center" prop="checkResult">
                    <template slot-scope="scope">
                      <div class="headerDiv">
                        <span>Ac={{ scope.row.acceptQty }},</span>
                        <span>Re={{ scope.row.rejectQty }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column label="参考图片" align="center" prop="referenceImage" width="260px" /> -->
                  <el-table-column label="检验记录" align="center" prop="analysisMethod" width="180px">
                    <template slot-scope="scope">
                      <div class="headerDiv" v-if="scope.row.analysisMethod=='1'">
                        <!-- {{ scope.row.analysisMethod == "1"?"有比较值":"/"}} -->
                        <span>目标值:{{ scope.row.targetVal }}</span>
                        <div>比较符{{ scope.row.compareSymbol == '1' ? '=' : '=' }}</div>
                        <span>上限差:{{ scope.row.upLimit }}</span>
                        <span>下限值:{{ scope.row.downLimit }}</span>
                        <span>上偏差:{{ scope.row.upOffset }}</span>
                        <span>下偏差:{{ scope.row.downOffset }}</span>
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column align="center" prop="checkResult" width="240px" label="检验结果">
                    <template slot-scope="scope">
                      <div v-if="scope.row.analysisMethod == '1'">
                        实际值:
                        <input v-model="scope.row.actualValue" />
                        <!-- <input v-model="scope.row.actualValue" /> -->
                      </div>
                      <el-radio-group v-model="scope.row.checkResult">
                        <el-radio :label="1" value="1">√</el-radio>
                        <el-radio :label="0" value="0">×</el-radio>
                      </el-radio-group>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>

              <el-form-item label="检验结果" prop="checkResult">
                  <el-radio-group v-model="form.checkResult">
                    <el-radio :label="1">√</el-radio>
                    <el-radio :label="0">×</el-radio>
                  </el-radio-group>
              </el-form-item>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注:" prop="remark">
                    <el-input 
                      v-model="form.remark" 
                      placeholder="输入备注" 
                      :autosize="{ minRows: 2, maxRows: 5 }" 
                      style="width: 450px; height: 100px" 
                      type="textarea"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <div style="margin-top: 20px;" v-if="form.checkResult == 0">
                <!-- <el-row
              
                  style="box-shadow: 0 0 7px rgb(186, 186, 186);padding:0 20px;margin-bottom:15px"
                >
                <el-col :span="24" class="imgDiv">-->
                
                <!-- </el-col> -->

                <!-- <el-col :span="24"> -->
                <el-form-item label="不合格品处理方式" prop="disposeType">
                  <el-radio-group v-model="form.disposeType">
                    <el-radio :label="0">返工/返修</el-radio>
                    <el-radio :label="1">挑选</el-radio>
                    <el-radio :label="2">让步</el-radio>
                    <el-radio :label="3">退货</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- </el-col>
                <el-col :span="24">-->
                <el-form-item label="检验记录">
                  <el-table :data="exceptionLogList">
                    <el-table-column label="类型选择" align="center" prop="indexType">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.indexType" placeholder="请选择检测项目" clearable>
                          <el-option
                            v-for="(dict,index) in abnormalList"
                            :key="index"
                            :label="dict"
                            :value="dict"
                          />
                        </el-select>
                      </template>
                    </el-table-column>

                    <el-table-column label="异常描述" align="center" prop="describeData">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.describeData" placeholder type="textarea" />
                      </template>
                    </el-table-column>
                    <el-table-column label="文件上传" align="center" prop="checkResult">
                      <template slot-scope="scope">
                        <ImageUpload
                          :limit="1"
                          :value="scope.row.sopUrl"
                          :fileSize="15"
                          @input="(url)=>handleImgUplaoded(url,scope.$index)"
                          @onRemoved="(url)=>handleImgRemoved(url,scope.$index)"
                        ></ImageUpload>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      align="center"
                      class-name="small-padding fixed-width"
                    >
                      <template slot-scope="scope">
                        <el-button
                          size="medium"
                          type="text"
                          icon="el-icon-circle-plus-outline"
                          @click="errorAdd()"
                        ></el-button>
                        <el-button
                          v-if="scope.$index != 0"
                          size="medium"
                          type="text"
                          icon="el-icon-remove-outline"
                          @click="errorDel(scope.$index)"
                        ></el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
                <!-- </el-col>
                </el-row>-->
              </div>
            </el-form>
          </div>

          <div class="demo-drawer__footer" style="text-align: right;">
            <el-button type="primary" @click="cancel" v-if="optType =='view'">返回</el-button>
            <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-drawer>

        <iqc-detail v-if="detailVisible" ref="detailOrUpdate"></iqc-detail>
      </div>
    </el-drawer>
  </div>
</template>
  
  <script>
import iqcDetail from "./iqc_detail.vue";
import {
  listIqc,
  getIqc,
  delIqc,
  addIqc,
  updateIqc,
  getinspectData,
  submitQcIqc
} from "@/api/mes/qc/iqc";
import ItemSelect from "@/components/itemSelect/single.vue";
import VendorSelect from "@/components/vendorSelect/single.vue";
import IqcLine from "./iqcline.vue";
import { genCode } from "@/api/mes/md/rule";
import { getReport, getReport2 } from "@/api/mes/report/report";
import { addItemrecpt, addItemrecptData } from "@/api/mes/wm/itemrecpt";
export default {
  name: "IqcIndex",
  dicts: ["mes_qc_result", "mes_order_status"],
  components: { ItemSelect, VendorSelect, IqcLine, iqcDetail },
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      acceptImg: require("@/assets/images/accept.png"),
      rejectImg: require("@/assets/images/reject.png"),
      prepareImg: require("@/assets/images/prepare.png"),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showFlag: false,
      // 总条数
      total: 0,
      // 来料检验单表格数据
      iqcList: [
        {
          inspectionNo: "1145522"
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        iqcCode: null,
        iqcName: null,
        headId: null
      },
      // 表单参数
      form: {},
      // 模板列表
      templateList: [],
      loading1: false,
      // 不合格数
      failedSncode: [],
      // 序列码集合
      snObj: {},
      //异常列表
      abnormalList: [],
      // 表单校验
      rules: {
        iqcCode: [
          { required: true, message: "来料检验单编号不能为空", trigger: "blur" }
        ],
        iqcName: [
          { required: true, message: "来料检验单名称不能为空", trigger: "blur" }
        ],

        vendorCode: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        itemCode: [
          { required: true, message: "物料不能为空", trigger: "blur" }
        ],
        quantityRecived: [
          { required: true, message: "本次接收数量不能为空", trigger: "blur" }
        ],
        quantityCheck: [
          { required: true, message: "本次检测数量不能为空", trigger: "blur" }
        ],
        reciveDate: [
          { required: true, message: "清选择来料日期", trigger: "blur" }
        ],
        inspectDate: [
          { required: true, message: "清选择检验日期", trigger: "change" }
        ]
      },
      //详情页面
      detailVisible: false,
      exceptionLogList: [{}]
    };
  },
  created() {
    // this.getList();
  },
  methods: {
    init(row) {
      console.log(row, "子组件的row");
      //调接口需要的id
      this.showFlag = true;
      this.queryParams.headId = row.id;
      this.getList();
    },

    /** 查询来料检验单列表 */
    getList() {
      this.loading = true;
      listIqc(this.queryParams).then(response => {
        this.iqcList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        iqcId: null,
        iqcCode: null,
        iqcName: null,
        templateId: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        vendorBatch: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityMinCheck: null,
        quantityMaxUnqualified: null,
        quantityRecived: null,
        quantityCheck: null,
        quantityUnqualified: null,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
        checkResult: null,
        reciveDate: null,
        inspectDate: null,
        inspector: null,
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.autoGenFlag = false;
      this.snObj = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.iqcId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    //检验
    handleView(row) {
      console.log(row, "rows");
      this.loading1 = false;
      this.open = true;
      this.form = { ...row };
      this.form.inspectDate = new Date();
      getinspectData(this.form).then(res => {
        console.log(res, "检查项检查内容dres");
        this.templateList = res.data.qcIqcInspectionItemList;
        this.getSpanArr(res.data.qcIqcInspectionItemList);
        this.abnormalList = this.templateList.map(item => {
          return item.inspectionItem;
        });
      });
    },
    // 判断当前是否是合格
    checkChange(value) {
      let failedIndex = 0;
      let failedSncode = [];
      let qualifiedCode = 0;
      for (let i = 0; i < this.form.quantitySpotCheck; i++) {
        let str = "checkResult" + i;
        let bool = this.templateList.every(item => item[str] != 0);
        if (!bool) {
          failedIndex++; //不合格数量
          failedSncode.push({
            snCode: this.snObj[`snCode${i}`],
            exceptionLogList: [{}]
          });
        } else {
          qualifiedCode++; //合格数量
        }
      }
      // this.form.quantityUnqualified = failedIndex; //不合格数量
      // this.form.receiveQty = qualifiedCode; //合格数量
      // this.failedSncode = failedSncode;
      // this.form.checkResult = failedIndex === 0 ? 1 : 0;
    },
    // 异常记录增加
    errorAdd() {
      let obj = {};
      this.exceptionLogList.push(obj);
    },
    // 删除异常记录
    errorDel(index) {
      this.exceptionLogList.splice(index, 1);
    },
    //图片上传成功
    handleImgUplaoded(imgUrl, index) {
      console.log(imgUrl, "=========");
      this.exceptionLogList[index].fileName = imgUrl;
      // this.form.sopUrl = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl, index) {
      console.log(imgUrl);
      this.exceptionLogList[index].fileName = null;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = { ...this.form };
          params.qcIqcInspectionItemList = this.templateList;
          let bool = false;
          for (let j = 0; j < this.templateList.length; j++) {
            const element = this.templateList[j].checkResult;
            console.log(element);
            if (element === undefined) {
              bool = true;
            }
          }
          if (bool) {
            this.$message({
              message: "请填写检验结果！！！",
              type: "warning"
            });
            return;
          }
          //检验结果和不合格检验方式等信息放在一个数组里
          console.log(this.failedSncode, "this.failedSncode");
          params.failedSncode = [
            {
              exceptionLogList: this.exceptionLogList,
              repairState: this.form.disposeType
            }
          ];

          console.log(params, "params");
          submitQcIqc(params).then(res => {
            console.log(res, "提交的res");
            if (res.code == 200) {
              this.$modal.msgSuccess("提交成功");
              this.open = false;
              this.reset();
              this.getList();
            } else {
              this.$modal.msgSuccess(res.msg);
            }
          });
        } else {
          this.$message({
            message: "请填写完整信息!",
            type: "warning"
          });
        }
      });
      // this.$refs["form"].validate(valid => {
      //   if (valid) {
      //     if (this.form.iqcId != null) {
      //       updateIqc(this.form).then(response => {
      //         this.$modal.msgSuccess("修改成功");
      //         //this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addIqc(this.form).then(response => {
      //         this.$modal.msgSuccess("新增成功");
      //         //this.open = false;
      //         this.form.iqcId=response.data;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    // //生成采购入库单接口
    // handleAddpurchasewarehousing(row){
    //   const iqcId = row.iqcId || this.ids
    //   getIqc(iqcId).then(response => {
    //     this.form = response.data;
    //     addItemrecptData(this.form).then(response => {
    //       this.$modal.msgSuccess("生成采购入库单成功");
    //       this.getList();
    //     });
    //   });
    // },

    // 详情页面
    viewReport(isEdit, row) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.detailOrUpdate.init(isEdit, row);
      });
    },

    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    //物料选择弹出框
    onItemSelected(obj) {
      debugger;
      if (obj != undefined && obj != null) {
        this.form.itemId = obj.jdyItemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
      }
    },
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      debugger;
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        this.form.vendorNick = obj.vendorNick;
      }
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("QC_IQC_CODE").then(response => {
          this.form.iqcCode = response;
        });
      } else {
        this.form.iqcCode = null;
      }
    },
    // 行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex !== 7) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            if (data[i].inspectionStandard === data[i - 1].inspectionStandard) {
              this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
            }
          }
        }
      }
    }
  }
};
</script>
  